var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    callback: {
        onClick: chooseClass
    }
};
var courseSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",

            rootPId: -1
        },
        key: {
            url: "nourl",
        }
    }
};
var ztree;
var courseTree;



function chooseClass(event, treeId, treeNode) {
    vm.courseName = treeNode.name;
    vm.courseId = treeNode.id
    vm.courseBody.courseId = treeNode.id
    vm.getCourseTree2()
    var colunms = CourseBody.initColumn();
    var table = new TreeTable(CourseBody.id, baseURL + "sys/coursebody/courseList?courseName=" + treeNode.id, colunms);
    table.setExpandColumn(2);
    table.setIdField("id");
    table.setCodeField("id");
    table.setParentCodeField("parentId");
    table.setExpandAll(false);
    table.init();
    CourseBody.table = table
    console.log(CourseBody.table);


}


/*function changeCourseToSmall(){
    var file = $("#changeSmall").val();
    if(file != "" && file != null){

        $.ajaxFileUpload({
            url:baseURL+"sys/coursebody/changeCourseToSmall",
            type:"POST",
            fileElementId: 'file',//file标签的id
            dataType: "json",
            global:true,
           // data:{headCode:'SumAmount'},
            complete:function () {
                    $.message.process('close'),
                        $("#changeSmall").val("")
            },
            success :function (r) {
               if(r.code(100)){
                   alert("上传成功")
               }else if (r.code(101)){
                   alert("请选择上传文件")
               }else{
                   alert(r.message)
               }
            }
        })

    }/!*else{
        alert("请选择上传文件")
        return
    }*!/

}*/

/*$("#changeSmall").upload({
    action:baseURL+"sys/coursebody/changeCourseToSmall", //表单提交的地址
    name:"file",
    autoSubmit:true,
    responseType:"json",
    onSubmit:function(file, extension){
        if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))){
            alert('只支持excel！');
            return false;
        }
    },
    onComplete:function (r) { //提交表单之后
        if(r.code(100)){
            alert("上传成功")
        }else if (r.code(101)){
            alert("请选择上传文件")
        }else{
            alert(r.message)
        }
    },
    onSelect: function() {//当用户选择了一个文件后触发事件
        //当选择了文件后，关闭自动提交
        this.autoSubmit=false;
        //校验上传的文件名是否满足后缀为.xls或.xlsx
        var regex =/^.*\.(?:xls|xlsx)$/i;
        //this.filename()返回当前选择的文件名称 (ps：我使用这个方法没好使，自己写了一个获取文件的名的方法) $("[name = '"+this.name()+"']").val())
        //alert(this.filename());
        if(regex.test($("[name = '"+this.name()+"']").val())){
            //通过校验
            this.submit();
        }else{
            //未通过
           // $("#myModal3").modal(); //错误提示框，文件格式不正确，必须以.xls或.xlsx结尾
            alert("文件格式不正确，必须以.xls或.xlsx结尾")
        }
    }
});*/




$(function () {
    vm.getCourseTree();
    new AjaxUpload('#changeSmall', {
        action:baseURL+"sys/coursebody/changeCourseToSmall",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))){
                alert('只支持excel！');
                return false;
            }
        },
        onComplete : function(file,r){
            if(r.code == 100){
                alert("导入成功")
                vm.reload()
            }else{
                alert(r.msg);
            }
        },
    });
});
var vm = new Vue({
    el: '#rrapp',
    data: {
        courseName: "",
        showList: true,
        title: null,
        searching: null,
        courseBody: {
            chapterName: null,
            courseName: null
        },
        course: {
            id: null,
            name: "",
            allName: ""
        },
        menu: {
            parentName: null,
            parentId: 0,
            type: 1,
            orderNum: 0,
            couresID: 0
        },
        menu2: {
            parentName: null,
            parentId: 0,
            type: 1,
            orderNum: 0,
            couresID: 0
        }
    },
    methods: {
        queryCourse: function () {
            vm.getCourseTree();
        },
        courseTree2: function () {
            vm.getCourseTree2();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#cLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = courseTree.getSelectedNodes();
                    //选择上级部门
                    vm.courseBody.courseName = vm.courseName;
                    console.log(vm.courseBody.course_name);
                    vm.courseBody.parentId = node[0].id;
                    vm.courseBody.parentName = node[0].name;
                    layer.close(index);
                }

            });
        },
        courseTree: function () {

            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    vm.getCourseTree();
                    var node = ztree.getSelectedNodes();
                    if (node[0].id < 10000) {
                        //选择上级菜单
                        vm.courseName = node[0].id;
                        var colunms = CourseBody.initColumn();
                        var table = new TreeTable(CourseBody.id, baseURL + "sys/coursebody/courseList?courseName=" + vm.id, colunms);
                        console.log(table)
                        table.setExpandColumn(2);
                        table.setIdField("id");
                        table.setCodeField("id");
                        table.setParentCodeField("parentId");
                        table.setExpandAll(false);
                        table.init();
                        CourseBody.table = table;
                        vm.getCourseTree();
                        layer.close(index);
                    }
                }
            });
        },
        changeToSmallCourse:function(){

        },
        getCourseTree: function (menuId) {
            //加载菜单树
            $.get(baseURL + "/course/menu/select?searching=" + vm.searching, function (r) {
                ztree = $.fn.zTree.init($("#courseTree"), setting, r.menuList);
                var node = ztree.getNodeByParam("id", vm.menu.parentId);
                ztree.selectNode(node);
            })


        },
        getCourseTree2: function () {
            //加载部门树
            $.get(baseURL + "sys/coursebody/selectGen?id=" + vm.courseId, function (r) {
                courseTree = $.fn.zTree.init($("#courseTree2"), courseSetting, r.deptList);

                var node = courseTree.getNodeByParam("id", vm.menu2.parentId);
                courseTree.selectNode(node);


            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            if (vm.courseName == null || vm.courseName == '') {
                if (vm.courseId == null || vm.courseId == '') {
                    alert('请先从左侧选择你要添加内容的课程！', function (index) {
                        vm.reload();
                    });
                }
            } else {
                vm.courseBody = {
                    type: 0,
                    parentId: null,
                    parentName: null,
                    courseName: vm.courseName,
                    dataType: "html",
                    courseId: vm.courseId
                };
            }
        },
        update: function (event) {
            var id = getSelectedRows1();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            var url = vm.courseBody.id == null ? "sys/coursebody/save" : "sys/coursebody/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.courseBody),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                            //   location. reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/coursebody/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            ('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "sys/coursebody/info/" + id, function (r) {
                vm.courseBody = r.courseBody;
            });
        },
        reload: function (event) {
            vm.showList = true;
            // var page = $("#jqGrid").jqGrid('getGridParam','page');
            // $("#jqGrid").jqGrid('setGridParam',{
            //     page:page
            // }).trigger("reloadGrid");
            CourseBody.table.refresh();
        }


    }

});

var CourseBody = {
    id: "courseTable",
    table: null,
    layerIndex: -1
};


/**
 * 初始化表格的列
 */
CourseBody.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle', width: '80px'},
        {title: '章节名称', field: 'chapterName', align: 'center', valign: 'middle', sortable: true, width: '180px'},
        {
            title: '类型', field: 'type', align: 'center', valign: 'middle', sortable: true, width: '60px',


            formatter: function (item, index) {
                if (item.type == 1) return '<span class="label label-warning ">讲义</span>'
                else return '<span class="label label-info">目录</span>'

            }
        },
        {
            title: '封面地址', field: 'coverPath', align: 'center', valign: 'middle', sortable: true, width: '100px',
            formatter: function (data) {
                return `<img src="${data}" style="height: 40px;width: 40px"></img>`;

            }
        },
        {
            title: '普清视频地址', field: 'videoPath', align: 'center', valign: 'middle', sortable: true, width: '100px',
            formatter: function (data) {
                if (data.videoPath != null) {
                    let htmlData
                    let video = data.videoPath.substring(0, 4)
                    if (video != 'http') {
                        video = 'https://' + data.videoPath
                    } else {
                        video = data.videoPath
                    }
                    if (data.type == 1)
                        htmlData = `<a href="${video}" target="_blank">播放</a>`
                    return htmlData;
                }

            }
        },
        {
            title: '高清视频地址', field: 'videoPath', align: 'center', valign: 'middle', sortable: true, width: '100px',
            formatter: function (data) {
                if (data.videoHdPath != null) {
                    let htmlData
                    let video = data.videoHdPath.substring(0, 4)
                    if (video != 'http') {
                        video = 'https://' + data.videoHdPath
                    } else {
                        video = data.videoHdPath
                    }
                    if (data.type == 1)
                        htmlData = `<a href="${video}" target="_blank">播放</a>`
                    return htmlData;
                }

            }
        },
        {title: '数据类型', field: 'dataType', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {
            title: '数据地址', field: 'dataPath', align: 'center', valign: 'middle', sortable: true, width: '100px',
            formatter: function (data) {
                if (data.dataPath != null) {
                    let htmlData
                    let video = data.dataPath.substring(0, 4)
                    if(video.match(".ppt")){
                        alert("现在仅支持pdf文件哦~")
                        return
                    }
                    if (video != 'http') {
                        video = 'https://' + data.dataPath
                    } else {
                        video = data.dataPath
                    }
                    if (data.type == 1)
                        htmlData = `<a href="${video}" target="_blank">查看</a>`
                    return htmlData;
                }

            }
        },
        {title: '介绍', field: 'introduce', align: 'center', valign: 'middle', sortable: true, width: '160px'},
        {
            title: '修改', field: 'id', align: 'center', valign: 'middle', sortable: true,


            formatter: function (item, index) {

                return '<span class="label label-warning" style="cursor:pointer;" onclick="update(' + item.id + ')">修改</span>';

            }
        },
        {
            title: '删除', field: 'id', align: 'center', valign: 'middle', sortable: true,


            formatter: function (item, index) {

                return '<span class="label label-warning" style="cursor:pointer;"  onclick="del(' + item.id + ')">删除</span>';

            }
        }
    ]

    return columns;
};


//选择多条记录
function getSelectedRows1() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if (!rowKey) {
        alert("请选择一条记录");
        return;
    }

    return grid.getGridParam("selarrrow");
}

function update(item) {
    var id = item;
    if (id == null) {
        return;
    }
    vm.showList = false;
    vm.title = "修改";
    vm.getInfo(id);
}

function del(item) {
    var ids = item;
    if (ids == null) {
        return;
    }

    confirm('确定要删除选中的记录？', function () {
        $.ajax({
            type: "POST",
            url: baseURL + "sys/coursebody/delete",
            contentType: "application/json",
            data: JSON.stringify(ids),
            success: function (r) {
                if (r.code == 0) {
                    alert('操作成功');
                    vm.reload()

                } else {
                    alert(r.msg);
                }

            }
        });
    });
}